package com.mj.mafeed.service;

import org.codehaus.jackson.map.ObjectMapper;

import android.content.Context;

import com.mj.mafeed.bean.MobileIndexJSON;
import com.mj.mafeed.bean.MobileIndexListJSON;
import com.mj.mafeed.config.Constants;
import com.mj.mafeed.dao.MobileIndexDao;
import com.mj.mafeed.util.HttpUtils;
import com.mj.mafeed.util.SPUtils;

/**
 * 手机端首页Service
 * @author zhaominglei
 * @date 2015-12-10
 * 
 */
public class MobileIndexService extends BaseService {
	private MobileIndexDao mobileIndexDao = new MobileIndexDao();
	
	/**
	 * 所有手机端首页
	 */
	public MobileIndexListJSON getAll() {
		StringBuilder url = new StringBuilder(Constants.MOBILEINDEX_ALL_URL);
		String result = HttpUtils.doGet(url.toString());
		if (result != null && !result.equals("")) {
			try {
				MobileIndexListJSON mobileIndexListJSON = new ObjectMapper().readValue(result, MobileIndexListJSON.class);
				return (mobileIndexListJSON != null) ? mobileIndexListJSON : null; 
			} catch (Exception e) {
				e.printStackTrace();
			}
		}		
		return null;
	}
	
	/**
	 * 同步手机端首页
	 */
	public void syncMobileIndex(Context context) {
		MobileIndexListJSON mobileIndexListJSON = getAll();
		if (mobileIndexListJSON != null 
				&& mobileIndexListJSON.getRecordList() != null 
				&& !mobileIndexListJSON.getRecordList().isEmpty()) {
			if (mobileIndexListJSON.getToutiao() != null && !mobileIndexListJSON.getToutiao().equals("")) {
				SPUtils.remove(context, "toutiao");
				SPUtils.put(context, "toutiao", mobileIndexListJSON.getToutiao());
			}
			mobileIndexDao.deleteAll(context);
			for (MobileIndexJSON mobileIndexJSON : mobileIndexListJSON.getRecordList()) {
				mobileIndexDao.save(context, mobileIndexJSON);
			}
		}
	}
	
	/**
	 * 根据类型获取手机端首页
	 */
	public MobileIndexListJSON getMobileIndex(Context context, String referer, int type) {
		MobileIndexListJSON mobileIndexListJSON = new MobileIndexListJSON();
		mobileIndexListJSON.setRecordList(mobileIndexDao.getMobileIndex(context, type));
		return mobileIndexListJSON;
	}
}
